import re
def count_patt(fname,patt):
    result = {}
    #为了更好的匹配效率，将正则表达式模式进行编译
    cpatt = re.compile(patt)
    with open(fname) as fobj:
        for line in fobj:
            m = cpatt.search(line)
            if m: #任何非空对象都是真
                key = m.group()
                result[key] = result.get(key, 0) + 1
    return result

if __name__ == '__main__':
    log_file  = 'access_log'
    ip = '^(\d+\.){3}\d+'
    br = 'Chrome|Firefox|MSIE'
    result1 = count_patt(log_file, ip)
    result2 = count_patt(log_file, br)
    print(result1)
    print(result2)






#文本文件用for循环，非文本用while循环
